package com.lzlg.lzlglab.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lzlg.lzlglab.entity.SmartDevice;
import com.lzlg.lzlglab.entity.SmartDeviceExample;
import com.lzlg.lzlglab.mapper.SmartDeviceMapper;
import com.lzlg.lzlglab.service.SmartDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SmartDeviceImpl implements SmartDeviceService {

    @Autowired
    SmartDeviceMapper smartDeviceMapper;

    @Override
    public PageInfo<SmartDevice> findAllByPage(Integer pageNum, Integer pageSize, String key, String typeId) {
        PageHelper.startPage(pageNum,pageSize);
        // 查询的时候有两个条件，第一个条件是名称，第二个条件是类型
        SmartDeviceExample example = new SmartDeviceExample();
        SmartDeviceExample.Criteria criteria = example.createCriteria();
        // 判断
        if(StrUtil.isNotEmpty(key)) {
            // where deviceName like '%key%'
            criteria = criteria.andDeviceNameLike("%" + key + "%");
        }
        if(StrUtil.isNotEmpty(typeId)){
            // where deviceType = typeId
            criteria = criteria.andDeviceTypeEqualTo(typeId);
        }
        return new PageInfo<>(smartDeviceMapper.selectByExample(example));
    }

    @Override
    public void saveOrUpdate(SmartDevice smartDevice) {
        String id = smartDevice.getId();
        if(StrUtil.isEmpty(id)){
            // 换一种id的形式 ObjectID
            String deviceId = IdUtil.objectId();
            smartDevice.setId(deviceId);
            smartDeviceMapper.insert(smartDevice);
        }else {
            smartDeviceMapper.updateByPrimaryKeySelective(smartDevice);
        }
    }

    @Override
    public void deleteById(String id) {
        smartDeviceMapper.deleteByPrimaryKey(id);
    }
}
